package cn.numeron.common.view

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.paging.LoadState
import androidx.paging.LoadStateAdapter
import androidx.recyclerview.widget.RecyclerView
import com.hedou.common.android.databinding.RecyclerItemPagingRetryBinding

class PagingRetryAdapter(private val retry: () -> Unit) :
    LoadStateAdapter<PagingRetryAdapter.ViewHolder>() {

    class ViewHolder(val viewBinding: RecyclerItemPagingRetryBinding) :
        RecyclerView.ViewHolder(viewBinding.root)

    override fun onBindViewHolder(holder: ViewHolder, loadState: LoadState) {
        holder.viewBinding.recyclerItemPagingRetryButton.isVisible = loadState is LoadState.Error
        holder.viewBinding.recyclerItemPagingProgressBar.isVisible = loadState is LoadState.Loading
    }

    override fun onCreateViewHolder(parent: ViewGroup, loadState: LoadState): ViewHolder {
        val layoutInflater = LayoutInflater.from(parent.context)
        val viewBinding = RecyclerItemPagingRetryBinding.inflate(layoutInflater, parent, false)
        viewBinding.recyclerItemPagingRetryButton.setOnClickListener {
            retry()
        }
        return ViewHolder(viewBinding)
    }

}